package com.beauty.user.service.impl;

import com.beauty.user.dto.LoginRequest;
import com.beauty.user.dto.LoginResponse;
import com.beauty.user.entity.User;
import com.beauty.user.repository.UserRepository;
import com.beauty.user.security.JwtTokenProvider;
import com.beauty.user.service.UserService;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtTokenProvider jwtTokenProvider;

    @Override
    public LoginResponse login(LoginRequest request) {
        User user = userRepository.findByUsername(request.getUsername())
                .orElseThrow(() -> new EntityNotFoundException("用户不存在"));

        if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            throw new BadCredentialsException("密码错误");
        }
        
        // 检查是否是商家登录请求
        if (Boolean.TRUE.equals(request.getIsMerchantLogin())) {
            // 如果请求是商家登录，但用户不是商家
            if (!Boolean.TRUE.equals(user.getIsMerchant())) {
                throw new BadCredentialsException("非商家账号，无法进行商家登录");
            }
        }

        String token = jwtTokenProvider.createToken(user);
        
        // 创建包含userId和customerId的LoginResponse
        LoginResponse response = new LoginResponse();
        response.setToken(token);
        response.setUserId(user.getId().toString());
        response.setCustomerId(user.getCustomerId());
        response.setUsername(user.getUsername());
        
        // 如果是商家账号，添加商家相关信息
        if (Boolean.TRUE.equals(user.getIsMerchant())) {
            response.setIsMerchant(true);
            response.setMerchantId(user.getMerchantId());
            response.setMerchantInfo(user.getMerchantInfo());
        } else {
            response.setIsMerchant(false);
        }
        
        return response;
    }

    @Override
    @Transactional
    public User register(User user) {
        if (userRepository.existsByUsername(user.getUsername())) {
            throw new IllegalArgumentException("用户名已存在");
        }
        if (userRepository.existsByEmail(user.getEmail())) {
            throw new IllegalArgumentException("邮箱已存在");
        }

        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userRepository.save(user);
    }

    @Override
    public User getUserById(Long id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("用户不存在，ID: " + id));
    }

    @Override
    public User getUserByCustomerId(String customerId) {
        return userRepository.findByCustomerId(customerId)
                .orElseThrow(() -> new EntityNotFoundException("用户不存在，客户ID: " + customerId));
    }

    @Override
    public User getUserByMerchantId(String merchantId) {
        return userRepository.findByMerchantId(merchantId)
                .orElseThrow(() -> new EntityNotFoundException("商家不存在，商家ID: " + merchantId));
    }

    @Override
    public List<User> getAllMerchants() {
        return userRepository.findByIsMerchantTrue();
    }
} 